<template>
    <f7-page @page:beforein="pageBeforeIn">
        <f7-navbar>
            <f7-nav-left :back-link="true" ></f7-nav-left>
            <f7-nav-title>问题整改</f7-nav-title>
            <f7-nav-right>
                <f7-badge color="red">待整改</f7-badge>&nbsp;&nbsp;
                <!-- <f7-badge color="pink" v-if="timeout">超时</f7-badge>-->
                <f7-badge color="yellow" v-if="isSendBack">退回</f7-badge>
            </f7-nav-right>
        </f7-navbar>

        <f7-list inline-labels no-hairlines no-hairlines-between inset v-if="isSendBack">
            <f7-list-item>
                <f7-label style="width:30%;">退回原因</f7-label>
                <f7-list-item-cell>
                    {{checkQualityProblem.sentBackRemark}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">退回照片</f7-label>
                <f7-list-item-cell>
                    <img width="80" height="80" style="margin-right: 5px;"
                         v-for="(imageFile, i) in checkQualityProblem.sentBackImageFile"
                         :src="imageFile.url" @click="$refs.sendBackShowPhotoBrowsers.open(i)">
                    </img>
                </f7-list-item-cell>
                <f7-photo-browser :photos="checkQualityProblem.sentBackImageFile"
                                  type="popup" ref="sendBackShowPhotoBrowsers" back-link-text="关闭">
                </f7-photo-browser>
            </f7-list-item>
        </f7-list>
        
        <f7-list inline-labels no-hairlines no-hairlines-between inset>
            <f7-list-item>
                <f7-label style="width:30%;">标段</f7-label>
                <f7-list-item-cell>
                    {{ $store.state.global.bidSectionMap[checkQualityProblem.bidSectionId].bid_section_name + '(' + $store.state.global.projectMap[$store.state.global.bidSectionMap[checkQualityProblem.bidSectionId].project_id].project_name + ')' }}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">部位</f7-label>
                <f7-list-item-cell v-if="$store.state.global.checkItemGuidelineMap[checkQualityProblem.problemClassId].process_mode == '1' ">
                    {{checkQualityProblem.buildingName + '栋' + checkQualityProblem.unitName + '单元'  + checkQualityProblem.floorName + '层' + checkQualityProblem.roomName}}
                </f7-list-item-cell>
                <f7-list-item-cell v-if="$store.state.global.checkItemGuidelineMap[checkQualityProblem.problemClassId].process_mode == '2' ">
                    {{checkQualityProblem.buildingName + '栋'  + checkQualityProblem.floorName +'层'}}
                </f7-list-item-cell>
                <f7-list-item-cell v-if="$store.state.global.checkItemGuidelineMap[checkQualityProblem.problemClassId].process_mode == '3' ">
                    {{checkQualityProblem.buildingName + '栋'}}
                </f7-list-item-cell>
                <f7-list-item-cell v-if="$store.state.global.checkItemGuidelineMap[checkQualityProblem.problemClassId].process_mode == '5' ">
                    {{checkQualityProblem.buildingName + '栋'  + checkQualityProblem.unitName + '单元'  + checkQualityProblem.floorName + '层'}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">检查项</f7-label>
                <f7-list-item-cell>
                    {{$store.state.global.problemClassMap[$store.state.global.problemClassMap[checkQualityProblem.problemClassId].parent_problem_class_id].problem_class_name
                    + ' - ' +
                    $store.state.global.problemClassMap[checkQualityProblem.problemClassId].problem_class_name}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">实测点</f7-label>
                <f7-list-item-cell>
                    {{checkQualityProblem.measurePoints}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">合格率</f7-label>
                <f7-list-item-cell>
                    {{checkQualityProblem.measurePoints == 0 ? 0 : formatPercent((checkQualityProblem.measurePoints - checkQualityProblem.problemPoints) / checkQualityProblem.measurePoints)}}%
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">爆点数值</f7-label>
                <f7-list-item-cell>
                    {{checkQualityProblem.problemPoints}}
                    <f7-link href="#" v-if="hasDrawingFile" @click="openHousePoint">户型图</f7-link>
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">检查人</f7-label>
                <f7-list-item-cell>
                    {{$store.state.global.userMap[checkQualityProblem.registBy].realname}}&nbsp;
                    {{problemText(checkQualityProblem.registDate)}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">问题描述</f7-label>
                <f7-list-item-cell>
                    {{checkQualityProblem.remark}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">问题照片</f7-label>
               	<f7-list-item-cell>
                    <img width="80" height="80" style="margin-right: 5px;"
                         v-for="(imageFile, i) in checkQualityProblem.imageFile"
                         :src="imageFile.url" @click="$refs.imageFile.open(i)">
                    </img>
                </f7-list-item-cell>
                <f7-photo-browser :photos="checkQualityProblem.imageFile"
                                  type="popup" ref="imageFile" back-link-text="关闭">
                </f7-photo-browser>
            </f7-list-item>
            <f7-list-item v-show="isRepairUser && isOnline" id="repairUserSmartSelect" smart-select
                          :smart-select-params="{openIn: 'popup', closeOnSelect: true, searchbar: true, searchbarPlaceholder: '搜索', searchbarDisableText: '取消', popupCloseLinkText: '返回'}">
                <f7-label>整改人</f7-label>
                <select v-model="form.repair.userId">
                    <optgroup label="施工单位">
                        <option v-for="(userId, i) in contractors" :key="userId"
                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
                        </option>
                    </optgroup>
                    <optgroup label="监理单位">
                        <option v-for="(userId, i) in supervisors" :key="userId"
                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
                        </option>
                    </optgroup>
                    <optgroup label="建设单位">
                        <option v-for="(userId, i) in constructors" :key="userId"
                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
                        </option>
                    </optgroup>
                </select>
            </f7-list-item>
            <f7-list-item v-show="!isRepairUser || !isOnline">
                <f7-label style="width:30%;">整改人</f7-label>
                <f7-list-item-cell>
	                {{$store.state.global.userMap[checkQualityProblem.repair].realname}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item  v-if="isRepairUser">
                <TakePhoto ref="refTakePhoto" @photoAdd="photoAdd" @photoDelete="photoDelete"></TakePhoto>
            </f7-list-item>
            <f7-list-item v-show="isRepairUser">
                <f7-input type="textarea" label="整改说明" placeholder="整改说明"
                          :value="form.remark" @change="form.remark = $event.target.value">
                </f7-input>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">抄送人</f7-label>
                <f7-list-item-cell>
                	<span v-for="(user, i) in checkQualityProblem.ccs" style="margin-right:4px;">
	                    {{$store.state.global.userMap[user].realname}}
	                </span>
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item v-show="isRepairUser">
            	<f7-list-item-cell>
                    <f7-button big round @click="saveTemporary">暂存</f7-button>
                </f7-list-item-cell>
                <f7-list-item-cell>
                    <f7-button big round fill color="blue" @click="ensureSunmit">完成整改</f7-button>
                </f7-list-item-cell>
            </f7-list-item>
        </f7-list>
    </f7-page>
</template>

<script>
import networkEvent from '@/mixins/networkEvent';
import back from '@/mixins/back.js';
import Common from "@/utils/Common.js";
import DateUtil from "@/utils/DateUtil.js";
import FileUtil from "@/utils/FileUtil.js";
import events from 'events';
import store from '@/store';
import { getUser, setUser, clearUser } from '@/utils/auth';
import { getStore, setStore, clearStore } from '@/utils/storage';
import { upload, uploadImage } from '@/utils/upload';
import keys from '@/utils/rememberKeys';
import request from '@/utils/request';
import db from '@/utils/db';
import TakePhoto from "@/components/TakePhoto.vue";

export default {
    store: store,
    mixins: [networkEvent, back ],
    props: {
    	checkQualityProblem: {
    		type: Object
    	}
    },
    components: {
        TakePhoto,
    },
    data: function() {
        return {
        	isOnline: false,
    		contractors: [],
    		supervisors: [],
    		constructors: [],
            form: {
            	tid: null,
            	problemId: '',
                photos: [],
                remark: '',
                repair: {
                    userId: '',
                }
            },
            deletePhotos: [],
        }
    },
    methods: {
    	pageBeforeIn: function() {
            this.isOnline = Common.isOnline();
        },
    	formatPercent: function(num) {
            return Math.floor(num * 1000) / 10;
        },
        photoAdd: function(cdvPath) {
    		this.form.photos.push(cdvPath);
    	},
    	photoDelete: function(cdvPath) {
    		for(var i = 0; i < this.form.photos.length; i++) {
    			if(cdvPath == this.form.photos[i]) {
    				this.form.photos.splice(i, 1);
                    if(cdvPath.indexOf('qualityMeasure') > -1) {
                        this.deletePhotos.push(cdvPath);
                    }
    				break;
    			}
    		}
    	},
    	problemText: function(date) {
            var text = '';
            if(date != null) {
            	text += DateUtil.dateToStr('yyyy-MM-dd HH:mm', date) + ' ';
            }
            return text;
        },
        openHousePoint: function() {
            var self = this;
            var drawingFile = self.checkQualityProblem.drawingFile[0];
            var router = self.$f7router.navigate('/HousePoint', {
                props: {
                    imageUrl: drawingFile.url,
                    pointCount: self.checkQualityProblem.problemPoints,
                    initialPoints: self.checkQualityProblem.problemValues,
                    editable: false,
                    hasPointValue: true
                }
            });
    	},
    	saveTemporary: function() {
    		var self = this;
    		let promises = [];
            self.deletePhotos.forEach(photo => {
    	        let promise = FileUtil.remove(photo).then(() => {
    	        	return Promise.resolve();
    	        }).catch((error) => {
    	        	console.error(error);
    	        	return Promise.resolve();
    	        });
    	        promises.push(promise);
    		});
            Promise.all(promises).then(() => {
    			let promises = [];
    			self.form.photos.forEach(photo => {
    				let promise = null;
    				if(photo.indexOf(Common.directory().qualityMeasure) < 0) {
    					let splits = photo.split('/');
    					let filename = splits[splits.length - 1];
    					let to = Common.directory().base + Common.directory().qualityMeasure + filename;
    					promise = FileUtil.copy(photo, to);
    				} else {
    					promise = new Promise((resolve, reject) => {
    						resolve(photo);
    					});
    				}
                    promises.push(promise);
    			});
    			return Promise.all(promises);
    		}).then((paths) => {
    			let photos = [];
    			paths.forEach(path => {
    				photos.push(path);
    			});
    			self.form.photos = photos;
    			this.$f7.dialog.confirm("是否确定暂存？", "", function() {
                    self.$f7.preloader.show();
                    let sql = "";
                    if(self.form.tid == null) {
                        sql = "\
                            insert into offline_quality_measure_repair( \
                            problem_id, offline_repair_image_file, \
                            offline_repair_remark) \
                            values (?, ?, ?) \
                        ";  
                    } else {
                        sql = "\
                            update offline_quality_measure_repair \
                            set problem_id = ?, offline_repair_image_file = ?, \
                            offline_repair_remark = ? \
                            where tid = '" + self.form.tid + "' \
                        ";
                    }
                    var values = [
                    	self.form.problemId,
                    	self.form.photos.join(','),
                    	self.form.remark
                    ];
                    Common.executeSql(sql, values).then((result) => {
                    	let rs = result.rs;
                    	var logStr = 'update'
                            + " offline_quality_measure_repair success! tid: "
                            + (self.form.tid == null ? rs.insertId : self.form.tid);
                        console.log(logStr);
                        self.$f7.dialog.alert('', '暂存问题成功！');
                        self.$f7router.back();
                        self.$f7.preloader.hide();
                    }).catch(error => {
            			console.error(error);
            			self.$f7.dialog.alert('', '暂存问题失败！');
                        self.$f7.preloader.hide();
            		});
                });
    		}).catch(error => {
    			console.error(error);
    			self.$f7.dialog.alert('', '暂存问题失败！');
    		});
    		
    	},
    	ensureSunmit: function() {
            var self = this;
            this.$f7.dialog.confirm("您确定完成整改？","",function() {
                self.submit();
            });
        },
        submit: function() {
        	var self = this;
            self.$f7.preloader.show();
            var data = {
            	photos: []
            };
            data.qualityMeasureCheckqualityProblemId = self.checkQualityProblem.qualityMeasureCheckqualityProblemId;
            data.repairUserId = getUser().userId;
            data.repairRemark = self.form.remark;
            let promises = [];
            let dialog = self.$f7.dialog.progress('上传图片中', 0);
            dialog.finishCount = 0;
            self.form.photos.forEach(photoPath => {
            	let promise = FileUtil.read(photoPath, 'image/jpeg').then(blob => {
            		let splits = photoPath.split("/");
            		let filename = splits[splits.length - 1];
            		return uploadImage(filename, blob);
            	}).then(result => {
            		data.photos.push({url: result.url});
            		dialog.finishCount++;
            		dialog.setProgress(parseInt(dialog.finishCount / (self.form.photos.length + 1)) * 100);
            		return Promise.resolve();
            	});
            	promises.push(promise);
            });
            Promise.all(promises).then((blobs) => {
            	return request({
            		url: '/rest/api/v3/qualityMeasureCheckQualityProblem/problemRepair',
            		method: 'post',
            		data: data
            	});
            }).then(result => {
            	dialog.close();
            	self.$f7.dialog.alert(result.msg, '问题修复成功！');
                self.$emit('problemStautsChange', result.element);
                self.$f7router.emit('problemStautsChange', result.element);
                if(self.form.tid != null) {
                	let sql = " \
                        delete from offline_quality_measure_repair \
                        where tid = '" + self.form.tid + "' \
                    ";
                	Common.executeSql(sql, []).then((result) => {
                		
                	}).catch(error => {
            			console.error(error);
            		});
                }
                self.$f7router.back();
                self.$f7.preloader.hide();
            	
            }).catch(error => {
            	dialog.close();
    			console.error(error);
    			self.$f7.dialog.alert( '','问题修复失败！');
                self.$f7.preloader.hide();
    		});
            
            
            
            /* var readerTags = self.form.photos.map(function(photo) {
                return false;
            });
            var emitter = new events.EventEmitter();
            emitter.on('readFinish', function() {
                for(var i = 0; i < readerTags.length; i++) {
                    if(!readerTags[i]) {
                        return;
                    }
                }
                Common.ajax({
                    type: 'POST',
                    url: Common.address + '/rest/api/v3/qualityMeasureCheckQualityProblem/problemRepair',
                    data: data,
                    xhrFields: {
                    	withCredentials: true
                    },
                    cache: false,
                    processData: false,
                    contentType: false,
                    dataType: "json",
                    success: function(result) {
                        self.$f7.dialog.alert(result.msg, '问题修复成功！');
                        self.$emit('problemStautsChange', result.element);
                        self.$f7router.emit('problemStautsChange', result.element);
                        if(self.form.tid != null) {
                            window.parent.db.transaction(function(tx) {
                                var sql = " \
                                    delete from offline_quality_measure_repair \
                                    where tid = '" + self.form.tid + "' \
                                ";
                                tx.executeSql(sql, [], function(tx, rs) {
                                    
                                });
                            }, function(error) {
                                console.error(error);
                            });
                        }
                        self.$f7router.back();
                        self.$f7.preloader.hide();
                    },
                    error: function() {
                    	self.$f7.dialog.alert(result.msg, '问题修复失败！');
                        self.$f7.preloader.hide();
                    }
                });
            });
            if(self.form.photos.length > 0) {
                for(var i = 0; i < self.form.photos.length; i++) {
                    (function(index) {
                        var photo = self.form.photos[index];
                        var xhr = new XMLHttpRequest();
                        xhr.open('GET', photo, true);
                        xhr.responseType = 'blob';
                        xhr.onload = function() {
                            if(this.status == 200) {
                                var blob = new Blob([this.response], {type: 'image/jpeg'});
                                data.append('photos', blob);
                                readerTags[index] = true;
                                emitter.emit('readFinish');
                            }
                        };
                        xhr.send();
                    })(i);
                }	
            } else {
            	emitter.emit('readFinish');
            } */
        },
    },
    computed: {
        isRepairUser: function () {
        	var currentUserId = getUser().userId;
            var user = this.checkQualityProblem.repair;
            if (user == currentUserId) {
                return true;
            }
            return false;
        },
        isSendBack: function() {
			if(this.checkQualityProblem.sentBackDate != null && this.checkQualityProblem.sentBackDate > 0) {
				return true;
			} else {
				return false;
			}
        },
        hasDrawingFile: function() {
            var drawingFile = this.checkQualityProblem.drawingFile;
            if(drawingFile == null || drawingFile.length == 0) {
                return false;
            } else {
                return true;
            }
        },
    },
    watch: {
    	'form.repair.userId': function (newVal, oldVal) {
            if (newVal != '' && oldVal != '') {
                var self = this;
                var param = {};
                param.qualityMeasureCheckqualityProblemId = self.checkQualityProblem.qualityMeasureCheckqualityProblemId;
                param.newRepairId = newVal;
                request({
            		url: '/api/qualityMeasureCheckQualityRepair/changeRepair',
            		method: 'GET',
            		params: param,
                    headers: {
    					'Content-Type': 'application/x-www-form-urlencoded'
    				}
            	}).then((result) => {
            		if (result.success) {
                        self.$f7.dialog.alert('修改整改人成功', '修改整改人成功');
                        self.$f7router.back();
                        self.$emit('problemChangeRepair', result.element);
                    	self.$f7router.emit('problemChangeRepair', result.element);
                    	if(self.form.tid != null) {
                    		window.parent.db.transaction(function(tx) {
                    			var sql = " \
                    			    delete from offline_quality_measure_repair \
                    			    where tid = '" + self.form.tid + "' \
                    			";
                    			tx.executeSql(sql, [], function(tx, rs) {
                    				
                    			});
                    		}, function(error) {
                    			console.error(error);
                    		});
                        } else {
                            self.checkQualityProblem.checkQualityProblemId = oldVal;
                            self.$f7.smartSelect.get('#repairUserSmartSelect .smart-select').setValue(
                                self.$store.state.global.userMap[oldVal].realname
                            );
                            self.$f7.dialog.alert('该问题已经由该人提交过来', '修改整改人失败');
                        }
            		}
            	}).catch(error => {
        			console.error(error);
        		});
            }
        }
    },
    created: function() {
    	var self = this;
        self.form.problemId = self.checkQualityProblem.qualityMeasureCheckqualityProblemId;
        self.form.repair.userId = self.checkQualityProblem.repair;
        let sql = "\
		    select * from offline_quality_measure_repair t \
		    where t.problem_id = '" + self.checkQualityProblem.qualityMeasureCheckqualityProblemId + "' \
		";
        Common.executeSql(sql, []).then((result) => {
        	let rs = result.rs;
        	if(rs.rows.length > 0) {
				let row = rs.rows.item(0);
				self.form.tid = row.tid;
				self.form.photos = 
					row.offline_repair_image_file == null || row.offline_repair_image_file == '' ? [] :
					row.offline_repair_image_file.split(',');
			    self.$refs.refTakePhoto.addPhotos(self.form.photos);
				self.form.remark = row.offline_repair_remark;
			}
        }).catch(error => {
			console.error(error);
		});
        
    },
    mounted: function () {
    	var self = this;
    	
        if (self.isRepairUser) {
            this.$nextTick(function () {
                if (self.$f7.smartSelect.get('#repairUserSmartSelect .smart-select') == undefined) {
                	self.$nextTick(function () {
                		self.$f7.smartSelect.get('#repairUserSmartSelect .smart-select').setValue(
               				self.$store.state.global.userMap[self.form.repair.userId].realname
                        );
                    });
                } else {
                	self.$f7.smartSelect.get('#repairUserSmartSelect .smart-select').setValue(
               			self.$store.state.global.userMap[self.form.repair.userId].realname
                    );
                }
            });
           
        }
        
        var projectId = self.$store.state.global.bidSectionMap[self.checkQualityProblem.bidSectionId].project_id;
        let sql = 
            "select id, app_permission " +
            "from tb_user " +
            "where id in ( "　+
            "    select user_id from tb_user_project where project_id = '" + projectId + "' " +
            ") " +
            "order by username "
        ;
        Common.executeSql(sql, []).then((result) => {
        	let rs = result.rs;
        	for(var i = 0; i < rs.rows.length; i++) {
                let row = rs.rows.item(i);
                if(row.app_permission == '施工单位') {
                	self.contractors.push(row.id);
                } else if(row.app_permission == '监理单位') {
                	self.supervisors.push(row.id);
                } else if(row.app_permission == '建设单位') {
                	self.constructors.push(row.id);
                }
            }
        }).catch(error => {
			console.error(error);
		});
    }
}
</script>

<style scoped>

</style>
